package com.chuangjiangx.member.manager.web.web.basic.controller;

import com.chuangjiangx.commons.response.CamelResponse;
import com.chuangjiangx.commons.response.ResponseUtils;
import com.chuangjiangx.member.basic.ddd.dal.dto.*;
import com.chuangjiangx.member.basic.ddd.dal.dto.count.MbrCountSubType;
import com.chuangjiangx.member.basic.ddd.query.MbrAnalysisQuery;
import com.chuangjiangx.member.manager.basic.web.controller.BaseController;
import com.chuangjiangx.member.manager.basic.web.interceptor.Login;
import com.chuangjiangx.member.manager.common.Constants;
import com.chuangjiangx.member.manager.common.ThreadLocalUser;
import com.chuangjiangx.member.manager.web.web.basic.request.MbrAanalysisRequest;
import com.chuangjiangx.member.manager.web.web.basic.response.AnalysisByChannelResponse;
import com.chuangjiangx.member.manager.web.web.basic.response.AnalysisResponse;
import com.chuangjiangx.member.stored.ddd.dal.condition.AppOrderCountCondition;
import com.sun.jmx.snmp.ThreadContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.ZoneId;
import java.util.List;


/**
 * 会员分析接口
 * @author cj-yzh
 * @date 2018/8/8 下午5：24MbrAanalysisRequest
 */

@RequestMapping(value = "/api/mbr/analysis")
@RestController
@Api(value = "会员总分析",tags = "会员分析")
public class MbrAnalysisController extends BaseController {

    @Autowired
    private MbrAnalysisQuery mbrAnalysisQuery;

    @ApiOperation(value = "总接口，会员分析",httpMethod = "GET")
    @Login
    @RequestMapping(value = "/consumer-analysis",method = RequestMethod.GET)
    public CamelResponse<AnalysisResponse> mbrAnalysis(MbrAanalysisRequest request){

        //获得登陆对象
        ThreadLocalUser token = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        Long merchantId = token.getMerchantId();
        //返回结果集
        AnalysisResponse response = new AnalysisResponse();
        //设置商户id
        response.setMerchantId(merchantId);
        //查询条件
        AppOrderCountCondition condition = new AppOrderCountCondition();
        condition.setStart(request.getStartTime());
        condition.setEnd(request.getEndTime());
        condition.setMerchantId(merchantId);
        //查询总人数和新增人数
        MbrCount mbrCount = mbrAnalysisQuery.queryCount(condition);
        response.setTotalMembers(mbrCount.getTotalMembers());
        response.setNewMembers(mbrCount.getNewMembers());
        response.setCountType(MbrCountSubType.TIME);
        //默认按时间查询
        List<TimeScales> timeScales = mbrAnalysisQuery.queryByTime(condition);
        int days = (int)Duration.between(
                request.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                request.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
        ).toDays();

        List<TimeScales> timeScales1 = formatTime(timeScales, days);
        response.setTimeScales(timeScales1);

        //会员活跃分析
        List<Actives> mbrActiveScales = mbrAnalysisQuery.queryByScope(condition);
        response.setMbrActiveScales(mbrActiveScales);
        return (CamelResponse)ResponseUtils.successCamel(response);
    }

    @ApiOperation(value = "根据渠道分析会员",httpMethod = "GET")
    @RequestMapping(value = "/consumer-analysis-sub",method = RequestMethod.GET)
    @Login
    public CamelResponse<AnalysisByChannelResponse> analysisByChannel(MbrAanalysisRequest request){
        //获得登陆对象
        ThreadLocalUser token = (ThreadLocalUser) ThreadContext.get(Constants.CURRENT_LOGIN_USER_KEY);
        Long merchantId = token.getMerchantId();
        //查询渠道
        String channel = request.getCountType();
        //返回结果集
        AnalysisByChannelResponse channelResponse = new AnalysisByChannelResponse();
        //设置商户id
        channelResponse.setMerchantId(merchantId);
        //设置查询渠道
        channelResponse.setCountType(channel);
        //查询条件
        AppOrderCountCondition condition = new AppOrderCountCondition();
        condition.setStart(request.getStartTime());
        condition.setEnd(request.getEndTime());
        condition.setMerchantId(merchantId);
        MbrCount mbrCount = mbrAnalysisQuery.queryCount(condition);
        //按终端查询
        MbrCountSubType mbrCountSubType = MbrCountSubType.valueOf(channel);
        switch (mbrCountSubType){
            case TERMINAL:
                List<TerminalScales> terminalScales = mbrAnalysisQuery.queryByTiminal(condition);
                for (TerminalScales terminalScale : terminalScales) {
                    terminalScale.setTotalMembers(mbrCount.getTotalMembers());
                }
                channelResponse.setRegistoryTerminalScale(terminalScales);
                break;
            case SEX:
                List<SexScales> sexScales = mbrAnalysisQuery.queryBySex(condition);
                channelResponse.setSexScale(sexScales);
                break;
            case TIME:
                List<TimeScales> timeScales = mbrAnalysisQuery.queryByTime(condition);
                int days = (int)Duration.between(
                        request.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(),
                        request.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
                ).toDays();
                List<TimeScales> timeScales1 = formatTime(timeScales, days);
                channelResponse.setTimeScales(timeScales1);
                break;
            case STORE:
                List<StoreScales> storeScales = mbrAnalysisQuery.queryByStore(condition);
                for (StoreScales storeScale : storeScales) {
                    storeScale.setTotalMembers(mbrCount.getTotalMembers());
                }
                channelResponse.setStoreScales(storeScales);
                break;


        }
        return (CamelResponse)ResponseUtils.successCamel(channelResponse);


    }

    //格式化时间
    private List<TimeScales> formatTime(List<TimeScales> timeScales,int days){
        if(days > 1){
            for (TimeScales timeScale : timeScales) {
                String timeStr = timeScale.getTimeStr();
                String year = timeStr.substring(0, 4);
                String month = timeStr.substring(4, 6);
                String day = timeStr.substring(6,8);
                String result = year+"-"+month+"-"+day;
                timeScale.setTimeStr(result);
            }
        }else {
            for (TimeScales timeScale : timeScales) {
                String timeStr = timeScale.getTimeStr();
                String result = timeStr.substring(8);
                result = result + ":00:00";
                timeScale.setTimeStr(result);
            }
        }
        return timeScales;
    }

}
